﻿using System.Collections.Generic;
using System.Linq;
using CrawlerCore;
using HtmlAgilityPack;

namespace WCrawlerLib
{
    public class BrowserSession_FileHost : BrowserSession
    {
        /// <summary>
        /// Check links are still alive or dead
        /// </summary>
        /// <param name="hostId"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        public Dictionary<string, string> CheckLinks(int hostId, string files)
        {
            string[] fileArray = files.Split(new char[] { '\n' });
            Dictionary<string, string> checklinks;
            if (hostId == (int)enumHost.Fileserve)
                checklinks = FileServeLinkChecker(fileArray);
            else if (hostId == (int)enumHost.Filesonic)
                checklinks = FileSonicLinkChecker(fileArray);
            else if (hostId == (int)enumHost.FileJungle)
                checklinks = FileJungleLinkChecker(fileArray);
            else if (hostId == (int)enumHost.FileFactory)
                checklinks = FileFactoryLinkChecker(fileArray);
            else if (hostId == (int)enumHost.DepositFiles)
                checklinks = LinkylookCheckLinks(fileArray, "http://linkylook.com/depositfiles-link-checker/");
            else
            {
                //checklinks = RapidLeech4uCheckLinks(fileArray);
                checklinks = UrlCheckerCheckLinks(fileArray);
                //checklinks = LinkylookCheckLinks(fileArray, hostId);
            }
            return checklinks;
        }

        private Dictionary<string, string> UrlCheckerCheckLinks(string[] fileArray)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            object objLock = new object();
            PostParams = "links=" + string.Join("\n", fileArray) +
                         "&submit=" + "Check Links";
            HtmlDocument doc = Post("http://urlchecker.net/");
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//table[@class='linkstable']//tr[td]");
            if (nodeCollection != null)
            {
                //foreach (HtmlNode node in nodeCollection)
                for (int i = 0; i < nodeCollection.Count; i++)
                {
                    HtmlNode node = nodeCollection[i];
                    string status = node.SelectSingleNode(@"./td[2]/text()").InnerHtml.Trim();
                    //string file = HttpUtility.UrlDecode(node.SelectSingleNode(@"./td[3]/a/text()").InnerHtml.Trim());
                    string file = fileArray[i];
                    lock (objLock)
                    {
                        result.Add(file, status);
                    }
                }
            }
            return result;
        }

        private Dictionary<string, string> LinkylookCheckLinks(string[] fileArray, string postUrl)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            PostParams = "linklist=" + string.Join("\n", fileArray);
            HtmlDocument doc = Post(postUrl);
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//*[@id='page_content']//tr[count(./td)>1]//a");
            if (nodeCollection != null)
            {
                for (int i = 0; i < nodeCollection.Count; i++)
                {
                    HtmlNode node = nodeCollection[i];
                    string status = "Working";
                    if (node.Attributes["style"] != null)
                        status = "Dead";
                    string file = fileArray[i];
                    result.Add(file, status);
                }
            }
            return result;
        }

        /// <summary>
        /// Check link in http://www.rapidleech4u.com/
        /// </summary>
        /// <param name="fileArray"></param>
        /// <returns></returns>
        private Dictionary<string, string> RapidLeech4uCheckLinks(string[] fileArray)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            PostParams = "submit=Check+Links&links=" + string.Join("\n", fileArray);
            HtmlDocument doc = Post("http://www.rapidleech4u.com/ajax.php?ajax=linkcheck");
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//*[@id='listlinks']//a");
            if (nodeCollection != null)
            {
                for (int i = 0; i < nodeCollection.Count; i++)
                {
                    HtmlNode node = nodeCollection[i];
                    string status = node.Attributes["title"].Value;
                    if (status == "Active")
                        status = "Working";
                    else
                        status = "Dead";
                    result.Add(fileArray[i], status);
                }
            }
            return result;
        }

        private Dictionary<string, string> WUploadLinkChecker(string[] fileArray)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            object objLock = new object();
            PostParams = "redirect=" + "/" +
                         "&links=" + string.Join("\n", fileArray) +
                         "&controls[submit]=" + "";

            HtmlDocument doc = Post("http://www.wupload.com/link-checker");
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//table[@id='files_status_tbl']//tr[td]");
            //foreach (HtmlNode node in nodeCollection)
            for (int i = 0; i < nodeCollection.Count; i++)
            {
                HtmlNode node = nodeCollection[i];
                string status = node.Attributes["class"].Value;
                if (status == "success")
                    status = "Working";
                else
                    status = "Dead";
                //string file = node.SelectSingleNode(@"./td[1]/span/text()").InnerHtml.Trim();
                string file = fileArray[i];
                lock (objLock)
                {
                    result.Add(file, status);
                }
            }
            return result;
        }

        /// <summary>
        /// Check links of FileSonic
        /// </summary>
        /// <param name="fileArray"></param>
        /// <returns></returns>
        private Dictionary<string, string> FileSonicLinkChecker(string[] fileArray)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            object objLock = new object();
            Get("http://www.filesonic.com/");
            PostParams = "redirect=" + "/" +
                         "&links=" + string.Join("\n", fileArray) +
                         "&controls[submit]=";
            HtmlDocument doc = Post(Response.ResponseUri.AbsoluteUri + "link-checker");
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//table[@id='files_status_tbl']//tr[td]");
            if (nodeCollection != null)
            {
                for (int i = 0; i < nodeCollection.Count; i++)
                {
                    HtmlNode node = nodeCollection[i];
                    string status = node.SelectSingleNode(@"./td[4]/span/strong/text()").InnerHtml.Trim();
                    if (status == "Available")
                        status = "Working";
                    else
                        status = "Dead";
                    string file = fileArray[i];// node.SelectSingleNode(@"./td[1]/span/text()").InnerHtml.Trim();
                    lock (objLock)
                    {
                        result.Add(file, status);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Check links of FileJungle
        /// </summary>
        /// <param name="fileArray"></param>
        /// <returns></returns>
        private Dictionary<string, string> FileJungleLinkChecker(string[] fileArray)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            object objLock = new object();
            PostParams = "urls=" + string.Join("\n", fileArray);
            HtmlDocument doc = Post("http://filejungle.com/check_links.php");
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//*[@id='left_content']/div[3]/div/ul/li");
            if (nodeCollection != null)
            {
                for (int i = 0; i < nodeCollection.Count; i++)
                {
                    HtmlNode node = nodeCollection[i];
                    string status = node.SelectSingleNode(@"./div[4]/span[2]").InnerHtml.Trim().ToLower();
                    if (status.Contains("not available"))
                        status = "Dead";
                    else
                        status = "Working";

                    string file = fileArray[i];// node.SelectSingleNode(@"./td[1]/span/text()").InnerHtml.Trim();
                    lock (objLock)
                    {
                        result.Add(file, status);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Check links of FileJungle
        /// </summary>
        /// <param name="fileArray"></param>
        /// <returns></returns>
        private Dictionary<string, string> FileServeLinkChecker(string[] fileArray)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            object objLock = new object();
            PostParams = "urls=" + string.Join("\n", fileArray) + "&ppp=201&submit=Check Urls";

            HtmlDocument doc = Post("http://fileserve.com/link-checker.php");
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//*[@id='container']/div[3]/div/div/table//tr");
            if (nodeCollection != null)
            {
                for (int i = 1; i < nodeCollection.Count; i++)
                {
                    HtmlNode node = nodeCollection[i];
                    string status = node.SelectSingleNode(@"./td[4]").InnerHtml.Trim().ToLower();
                    if (status.Contains("not available"))
                        status = "Dead";
                    else
                        status = "Working";
                    string file = fileArray[i - 1];
                    lock (objLock)
                    {
                        result.Add(file, status);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Check links of FileJungle
        /// </summary>
        /// <param name="fileArray"></param>
        /// <returns></returns>
        private Dictionary<string, string> FileFactoryLinkChecker(string[] fileArray)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            foreach (string file in fileArray)
                result.Add(file, "Dead");

            PostParams = "func=links&links=" + string.Join("\n", fileArray);
            HtmlDocument doc = Post("http://www.filefactory.com/tool/links.php");
            HtmlNodeCollection nodeCollection = doc.DocumentNode.SelectNodes(".//*[@id='content']//table//a");
            if (nodeCollection != null)
            {
                for (int i = 0; i < nodeCollection.Count; i++)
                {
                    HtmlNode node = nodeCollection[i];

                    for (int j = 0; j < fileArray.Count(); j++)
                    {
                        if (node.Attributes["href"].Value.Contains(fileArray[j]))
                        {
                            result[fileArray[j]] = "Working";
                            break;
                        }
                    }
                }
            }
            return result;
        }
    }
}